import { plugin, Messagetype } from 'alemon'
import db from '../../db/sqlite/config.js'
import { QueryTypes } from 'sequelize'

const context: Record<string, any> = {} //添加图片上下文
const contextTimer: Record<string, any> = {} //记时
export class K_gjcAdd extends plugin {
  constructor() {
    super({
      dsc: '关键词列表',
      priority: 500,
      rule: [
        {
          reg: '^/添加(.*)$',
          fnc: 'add'
        },

        {
          reg: /(.*)/,
          fnc: 'addContent'
        }
      ]
    })

    // 创建表
    db.query(`CREATE TABLE IF NOT EXISTS k_gjc
        (
          "key" TEXT NOT NULL,
          "value" TEXT NOT NULL,
          "guild" TEXT NOT NULL
        )
     `)
  }
  async add(e: Messagetype) {
    const eventType = e.eventId.split(':')[0]
    // 只允许私域消息
    if (eventType !== 'MESSAGE_CREATE') {
      return
    }

    // 1	全体成员
    // 2	管理员
    // 4	群主/创建者
    // 5	子频道管理员
    // 没有权限
    if (
      !e.msg.member.roles.includes('4') &&
      !e.msg.member.roles.includes('5') &&
      !e.msg.member.roles.includes('2')
    ) {
      await e.reply(`<@!${e.msg.author.id}> 无权限`)

      return true
    }
    const msg = e.msg.content
      .substring(e.msg.content.indexOf('/添加'), e.msg.content.length)

      .replace('/添加', '')
      .trim()

    // console.log(msg)

    if (msg === '') {
      await e.reply(`<@!${e.msg.author.id}> 内容不能为空!`)
      return true
    }
    //上下文添加

    if (!context[e.msg.guild_id]) {
      context[e.msg.guild_id] = {}
    }
    context[e.msg.guild_id][e.msg.author.id] = {
      text: msg
    }

    await e.reply(`<@!${e.msg.author.id}> 请发送内容!`)
    if (!contextTimer[e.msg.guild_id]) {
      contextTimer[e.msg.guild_id] = {}
    }

    contextTimer[e.msg.guild_id][e.msg.author.id] = setTimeout(async () => {
      if (context[e.msg.guild_id][e.msg.author.id]) {
        delete context[e.msg.guild_id][e.msg.author.id]

        await e.reply(`<@!${e.msg.author.id}> 添加已取消!`)
      }
    }, 120 * 1000)
    return true
  }

  async addContent(e: Messagetype) {
    const eventType = e.eventId.split(':')[0]
    // 只允许私域消息
    if (eventType !== 'MESSAGE_CREATE') {
      return
    }

    if (!context[e.msg.guild_id] || !context[e.msg.guild_id][e.msg.author.id]) {
      return false
    }

    const data = await db
      .query('select * from k_gjc where guild = ? and key = ? ', {
        replacements: [e.msg.guild_id, context[e.msg.guild_id][e.msg.author.id].text],
        type: QueryTypes.SELECT
      })
      .catch(err => err.parent)

    if ('errno' in data) {
      clearTimeout(contextTimer[e.msg.guild_id][e.msg.author.id])
      delete contextTimer[e.msg.guild_id][e.msg.author.id]
      delete context[e.msg.guild_id][e.msg.author.id]
      return e.reply('查询数据库失败')
    }
    // 存在 更新
    if (data[0]) {
      await db.query('UPDATE k_gjc SET value = ? WHERE key = ? and guild = ?', {
        replacements: [
          JSON.stringify({
            content: e.msg.content ? e.msg.content : undefined,
            image: e.msg.attachments ? e.msg.attachments : undefined
          }),
          context[e.msg.guild_id][e.msg.author.id].text,
          e.msg.guild_id
        ],
        type: QueryTypes.UPDATE
      })
    } else {
      // 添加

      await db.query('INSERT INTO k_gjc (key, value, guild) VALUES (?, ?, ?)', {
        replacements: [
          context[e.msg.guild_id][e.msg.author.id].text,
          JSON.stringify({
            content: e.msg.content ? e.msg.content : undefined,
            image: e.msg.attachments ? e.msg.attachments : undefined
          }),
          e.msg.guild_id
        ],
        type: QueryTypes.INSERT
      })
    }

    await e.reply(`<@!${e.msg.author.id}> 添加成功!`)

    clearTimeout(contextTimer[e.msg.guild_id][e.msg.author.id])
    delete contextTimer[e.msg.guild_id][e.msg.author.id]
    delete context[e.msg.guild_id][e.msg.author.id]
    return true
  }
}
